package com.cyys.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyys.entity.MiniUser;
import com.cyys.entity.Sites;
import com.cyys.response.Result;
import com.cyys.service.MiniUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Long
 * @since 2022-06-13
 */
@RestController
@RequestMapping("/mini_user")
public class MiniUserController {
    @Autowired
    private MiniUserService miniUserService;

    @RequestMapping(value = "/user",method = GET)
    public Result findUserId(@RequestParam(value = "openid") String openid){
        MiniUser miniuser = miniUserService.selectUserByOpenId(openid);
        return Result.ok().data("miniuser",miniuser);
    }



    @ResponseBody
    @RequestMapping(value = "/login",method = POST)
    public Result getOpenid(@RequestParam(value="code",required=false)String code, @RequestParam(value = "imgurl")String imgurl,
                            @RequestParam(value = "nickname")String nickname, @RequestParam(value = "sex")String sex){

        //微信官方提供获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        //替换appid，appsecret，和code
        String requestUrl = WX_URL.replace("APPID", "wxa10fbb469a5b478a").//填写自己的appid
                replace("SECRET", "e1d7dc88a78c11d52cca53d470cc41a6").replace("JSCODE", code).//填写自己的appsecret，
                replace("authorization_code", "authorization_code");
        //定义json对象
        JSONObject convertvalue=new JSONObject();
        //调用get方法
        String  returnvalue=GET(requestUrl);
        //解析返回值，对象解析成字符串
        convertvalue= (JSONObject) JSON.parse(returnvalue);
        String session_key= (String) convertvalue.get("session_key");
        String openid= (String) convertvalue.get("openid");
        MiniUser user1 = miniUserService.selectUserByOpenId(openid);//判断数据库中是否已存在
        if(user1==null){//不存在就存入数据库
            MiniUser user=new MiniUser();
            user.setSex(sex);
            user.setOpenid(openid);
            user.setImg_url(imgurl);
            user.setNickname(nickname);
            user.setPassword("123456");
            user.setSession_key(session_key);
            miniUserService.save(user);
        }else{
            System.out.println("用户已存在，请登录");
        }
        System.out.println(returnvalue);//打印测试
        System.out.println("openid:"+openid);//打印测试
        System.out.println("session_key:"+session_key);//打印测试

      return   Result.ok().data("openid",openid);

    }
    //发起ge请求---生成openid和session_key
    public  String GET(String url) {
        String result="";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try{
            //构造url对象
            URL realUrl = new URL(url);
            //获取一个对应该URL的URLConnection对象
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常出现");
        }
        //关闭资源
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现异常");
            }
        }
        return result;
    }

    @GetMapping("/updatesites")
    public Result updatesitesCart(@RequestParam(name = "id", value = "id") Integer id,
                                 @RequestParam(name = "nickname", value = "nickname", required = false) String nickname,
                                 @RequestParam(name = "sex", value = "sex", required = false) String sex,
                                 @RequestParam(name = "img_url", value = "img_url", required = false) String img_url
                                  ) {

        MiniUser s = new MiniUser();
        s.setId(id);
        s.setNickname(nickname);
        s.setSex(sex);
        s.setImg_url(img_url);
        UpdateWrapper up=new UpdateWrapper();
        up.eq("id",id);
        boolean update = miniUserService.update(s, up);
        if (update) {
            return Result.ok().message("修改信息成功");
        }
        return Result.error().message("修改信息失败");

    }

    @RequestMapping(value = "/findId",method = GET)
    public Result findId(@RequestParam(value = "id") Integer id){
        MiniUser list = miniUserService.getById(id);
        return Result.ok().data("list",list);
    }



}

